import router from '@/router'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import getPageTitle from '@/utils/get-page-title'

const whiteList = ['/login', '/404']

// 拿到要去的页面的 title，赋值给 document.title
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  if (store.getters.token) {
    if (to.path === '/login') {
      NProgress.done()
      next('/')
    } else {
      if (!store.getters.userId) {
        const { roles: { menus }} = await store.dispatch('user/getUserInfo')
        const otherRoutes = await store.dispatch('permissions/filterRoutes', menus)
        router.addRoutes([...otherRoutes, { path: '*', redirect: '/404', hidden: true }])
        next({
          ...to,
          replace: true
        })
        return
      }
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      NProgress.done()
      next('/login')
    }
  }
})

router.afterEach((to) => {
  // document.title = '人资管理系统-' + to.meta.title
  document.title = getPageTitle(to.meta.title)
  NProgress.done()
})
